package top.winshu.common.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import top.winshu.common.exception.WinshuParseException;

import java.util.List;
import java.util.Optional;

/**
 * @author winshu
 * @since 2021/6/7
 **/
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object object) {
        try {
            return objectMapper().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new WinshuParseException(e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return objectMapper().readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new WinshuParseException(e);
        }
    }

    public static <E> List<E> fromArrayJson(String json, Class<E> clazz) {
        JavaType javaType = objectMapper().getTypeFactory().constructCollectionType(List.class, clazz);
        try {
            return objectMapper().readValue(json, javaType);
        } catch (JsonProcessingException e) {
            throw new WinshuParseException(e);
        }
    }

    public static JsonNode parseObject(String json) {
        try {
            return objectMapper().readTree(json);
        } catch (JsonProcessingException e) {
            throw new WinshuParseException(e);
        }
    }

    public static ObjectMapper objectMapper() {
        return Optional.ofNullable(SpringContextUtil.getBean(ObjectMapper.class)).orElse(objectMapper);
    }

    public static void main(String[] args) {
        String json = "{\"user\": {\"code\": \"abc\", \"age\": 19}}";
        System.out.println(JsonUtil.parseObject(json).get("user").toString());
    }
}
